package com.eorchis.module.addUser.dao.Impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Repository;
import com.eorchis.constants.RoleConstants;
import com.eorchis.core.basedao.dao.impl.HibernateAbstractBaseDao;
import com.eorchis.core.basedao.query.condition.IPagingQueryCondition;
import com.eorchis.core.basedao.query.condition.builder.IConditionBuilder;
import com.eorchis.core.basedao.query.condition.builder.impl.DefaultQueryConditionBuilder;
import com.eorchis.module.addUser.bean.DepartmentBean;
import com.eorchis.module.addUser.bean.UserBean;
import com.eorchis.module.addUser.dao.IAddUserDao;
import com.eorchis.module.addUser.ui.commond.UserQueryCommond;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: IAuditingDao<br>
 * Description: 部委选人接口实现<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * 
 * @author RongSL
 * @createDate 2016-09-12
 * @version $Revision$
 */
@SuppressWarnings("unchecked")
@Repository(value = "com.eorchis.module.addUser.dao.Impl.AddUserImpl")
public class AddUserDaoImpl extends HibernateAbstractBaseDao implements IAddUserDao {

	/**
	 * 获得UUM中loginId最小编号
	 * @author RongSL
	 * @Date 2016-09-15
	 * */
	public String getUumMinLoginid(String depCode){
		Map<String,Object> params=new HashMap<String,Object>();
		String sql=" select min(u.LOGIN_ID)  as loginId from UUM_SYSTEM_ROLE_SCOPES@UUM_LINK rs  " +
				"inner join UUM_SYSTEM_ROLE@UUM_LINK r on rs.ROLE_ID = r.ROLE_ID " +
				"inner join UUM_SYSTEM@UUM_LINK us on r.system_id = us.system_id  " +
				"inner join UUM_CONTROLSCOPE@UUM_LINK uc on rs.CONTROLSCOPE_ID = uc.CONTROLSCOPE_ID " +
				"inner join UUM_DEPARTMENT@UUM_LINK d on uc.DEPID = d.DEPID " +
				"inner join UUM_USER@UUM_LINK u on uc.USERID = u.USERID " +
				"where  us.system_id = :systemId and u.login_id like :loginId and u.login_id <= '455999777'";
//		params.put("depCode", depCode);
		params.put("systemId", RoleConstants.XT_CODE);
//		params.put("BwCode", RoleConstants.ROLE_CODE_BW_ADMIN);
		params.put("loginId", depCode+999+"%");
		List<?> l=this.executeFind(QueryStringType.SQL, sql, params);
		String id;
		if(PropertyUtil.objectNotEmpty(l)&&PropertyUtil.objectNotEmpty(l.get(0))){
			id=(Integer.valueOf(l.get(0).toString())-1)+"";
		}else{
			id=depCode+"999777";
		}
		return id;
	}
	
	/**
	 * 获得uum中的指定序列
	 * @author RongSL
	 * @Date 2016-09-15
	 * */
	public String getUumSeq(String strings){
		Map<String,Object> params=new HashMap<String,Object>();
		String sql=" select Last_Number-INCREMENT_BY from user_sequences@uum_link where sequence_name=:seq ";
		params.put("seq", strings);
		List<?> l=this.executeFind(QueryStringType.SQL, sql, params);
		if(PropertyUtil.objectNotEmpty(l)){
			String id=l.get(0).toString();
			return (Integer.valueOf(id)+1)+"";
		}else{
			return UUID.randomUUID().toString();
		}
	}

	/**
	 * 按数量新增部委
	 * @Date 2016-09-14
	 * @author RongSL
	 * */
	@Override
	public boolean addBwAdmin(UserQueryCommond commond) {
		boolean flag=true;
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("activeState", UserBean.ACTIVE_ENABLED);
		//添加管理员
		for(int q=0;q<commond.getUserNumber();q++){
			try{
				StringBuffer sb1=new StringBuffer(" insert into uum_user@uum_link      " +
						"(userid,login_id,password,user_name,sex_code,"+
						"create_date,folk_code,paper_type_code,politices_code,"+
						"degree_code,duty_level_code,duty_code,zugong,"+
						"exam_state,chisel_state,admin_state,student_state,"+
						"teacher_state,active_state,order_num,last_operate_time,"+
						"last_operate_type,is_bureau_reserve,availability_state,shiguan,"+
						"view_state,dangwu,tongzhan)values(uum_user_seq.nextval@uum_link,"+
						":loginIdSeq,:passWord,:loginIdSeq,1078,sysdate,"+
						"1000,1222,1175,1191,1380,1390,0,0,0,0,"+
						"1,0,1,0,sysdate,2,0,1,0,1,0,0)");
				params.put("loginIdSeq", getUumMinLoginid(commond.getSearchDepCode()));
//				params.put("userIdSeq", UserBean.uumUserSeq);
				params.put("passWord", UserBean.defaultPassWord);
				int i=this.executeUpdate(QueryStringType.SQL, sb1.toString(), params);
				if(i<1){
					flag=false;
				}
			}catch(Exception e){
				flag=false;
				System.out.println("添加部委出错！");
				e.printStackTrace();
			}
			//初始化所在部门
			try{
				StringBuffer sb2=new StringBuffer(" insert into uum_department_user@uum_link " +
						"(depuser_id, userid, depid, active_state, last_operate_time, last_operate_type) " +
						"values (uum_department_user_seq.nextval@uum_link, uum_user_seq.currval@uum_link, :depId, :activeState,  sysdate, 2) ");
//				params.put("depIdSeq", DepartmentBean.uumDepartmentSeq);
//				params.put("userIdCurrSeq", UserBean.uumUserCurrSeq);
				params.put("depId", commond.getDepId());
				int i=this.executeUpdate(QueryStringType.SQL, sb2.toString(), params);
				if(i<1){
					flag=false;
				}
			}catch(Exception e){
				flag=false;
				System.out.println("初始化部门出错！");
				e.printStackTrace();
			}
			//添加管理范围
			try{
				StringBuffer sb2=new StringBuffer(" insert into UUM_CONTROLSCOPE@UUM_LINK values " +
						"( UUM_CONTROLSCOPE_SEQ.nextval@UUM_LINK, :depId, uum_user_seq.currval@uum_link, null, null, :activeState)");
				int i=this.executeUpdate(QueryStringType.SQL, sb2.toString(), params);
				if(i<1){
					flag=false;
				}
			}catch(Exception e){
				flag=false;
				System.out.println("添加管理范围出错！");
				e.printStackTrace();
			}
			//添加系统角色关联
			try{
				StringBuffer sb2=new StringBuffer(" insert into UUM_SYSTEM_ROLE_SCOPES@UUM_LINK values " +
						"(UUM_SYSTEM_ROLE_SCOPE_SEQ.nextval@UUM_LINK, 1, :roleId, UUM_CONTROLSCOPE_SEQ.currval@UUM_LINK)");
				params.put("roleId", RoleConstants.BW_ROLE_ID);
				int i=this.executeUpdate(QueryStringType.SQL, sb2.toString(), params);
				if(i<1){
					flag=false;
				}
			}catch(Exception e){
				flag=false;
				System.out.println("添加系统角色关联出错！");
				e.printStackTrace();
			}
		}
		return flag;
	}

	/**
	 * 启用/作废部委
	 * @Date 2016-09-14
	 * @author RongSL
	 * */
	@Override
	public boolean EnableBwAdmin(UserQueryCommond commond) {
		boolean flag=true;
		Map<String,Object> params=new HashMap<String,Object>();
		try{
			StringBuffer sql=new StringBuffer(" update UUM_USER@uum_link u set u.active_state=:state where u.userid in (:userIds)");
			params.put("userIds", commond.getSearchUserIds());
			params.put("state", commond.getSearchEnableState());
			int i=this.executeUpdate(QueryStringType.SQL, sql.toString(), params);
			if(i<1){
				flag=false;
			}
		}catch(Exception e){
			System.out.println("启用/作废部委失败！");
			e.printStackTrace();
			flag=false;
		}
		return flag;
	}

	/**
	 * 按条件查询部委
	 * @Date 2016-09-14
	 * @author RongSL
	 * */
	@Override
	public List<UserBean> findBwAdmin(UserQueryCommond commond) {
		Map<String,Object> params=new HashMap<String,Object>();
		StringBuffer sql=new StringBuffer(" select to_char(u.userid)    as \"userId\",  u.LOGIN_ID  as \"loginId\", u.USER_NAME as \"userName\", " +
				"d2.DEPNAME  as \"depName\", d.DEPNAME   as \"scopesdepName\",to_char(u.create_date,'yyyy-MM-dd hh24:mm:ss') as \"createDateStr\", r.role_name as \"roleName\", " +
				"r.role_code as \"roleCode\", to_char(d2.depid) as \"depId\",  d.depcode as \"depCode\",u.active_state as \"activeState\" " +
				"from UUM_SYSTEM_ROLE_SCOPES@UUM_LINK rs " +
				"inner join UUM_SYSTEM_ROLE@UUM_LINK r on rs.ROLE_ID = r.ROLE_ID  " +
				"inner join UUM_SYSTEM@UUM_LINK us on r.system_id = us.system_id  " +
				"inner join UUM_CONTROLSCOPE@UUM_LINK uc on rs.CONTROLSCOPE_ID = uc.CONTROLSCOPE_ID  " +
				"inner join UUM_DEPARTMENT@UUM_LINK d on uc.DEPID = d.DEPID " +
				"inner join UUM_USER@UUM_LINK u on uc.USERID = u.USERID, UUM_DEPARTMENT_USER@UUM_LINK udu " +
				"inner join UUM_USER@UUM_LINK u2 on udu.USERID = u2.USERID " +
				"inner join UUM_DEPARTMENT@UUM_LINK d2 on udu.DEPID = d2.DEPID " +
				"where udu.USERID = u.USERID and us.system_id =:systemId  and us.active_state = :activeState " +
				"and rs.ACTIVE_STATE = :activeState  and r.ACTIVE_STATE = :activeState and uc.ACTIVE_STATE = :activeState and d.ACTIVE_STATE = :activeState  " +
				"and udu.ACTIVE_STATE = :activeState and d2.active_state = :activeState ");
		if(PropertyUtil.objectNotEmpty(commond.getSearchDepCode())){
			sql.append(" and d.depcode=:depCode ");
			params.put("depCode", commond.getSearchDepCode());
		}
		if(PropertyUtil.objectNotEmpty(commond.getSearchLoginId())){
			sql.append(" and u.login_id=:loginId ");
			params.put("loginId", commond.getSearchLoginId());
		}
		if(PropertyUtil.objectNotEmpty(commond.getSearchEnableState())){
			sql.append(" and uc.ACTIVE_STATE =:activeState ");
			params.put("activeState",commond.getSearchEnableState());
		}
		if(PropertyUtil.objectNotEmpty(commond.getSearchUserName())){
			sql.append(" and u.user_name like :userName ");
			params.put("userName", "%"+commond.getSearchUserName()+"%");
		}
		if(PropertyUtil.objectNotEmpty(commond.getRoleCode())){
			sql.append(" and r.role_code =:roleCode ");
			params.put("roleCode",RoleConstants.ROLE_CODE_BW_ADMIN );
		}
		sql.append(" order by u.login_id desc ");
		params.put("activeState", UserBean.ACTIVE_ENABLED);
		params.put("systemId", RoleConstants.XT_CODE);
		List<UserBean> list;
		IConditionBuilder defaultQueryConditionBuilder  = new DefaultQueryConditionBuilder();
		defaultQueryConditionBuilder.setBaseQueryString(sql.toString());
		defaultQueryConditionBuilder.setQueryStringType(QueryStringType.SQL);
		defaultQueryConditionBuilder.setResultObject(UserBean.class);
		IPagingQueryCondition queryCondition = (IPagingQueryCondition) defaultQueryConditionBuilder.buliderQueryCondition();
		queryCondition.setParameters(params);
		
		if(commond.getPage()==-1){
			 list = (List<UserBean>) this.findList(queryCondition);
		}else{
			 Long count = this.count(queryCondition);
			 int firstResult = commond.calculate(count.longValue());
			 list = (List<UserBean>) this.findList(queryCondition,firstResult, commond.getLimit());
		}
		return list;
	}

	/**
	 * 重置指定部委密码
	 * @Date 2016-09-14
	 * @author RongSL
	 * */
	@Override
	public boolean resetBwAdmin(UserQueryCommond commond) {
		boolean flag=true;
		Map<String,Object> params=new HashMap<String,Object>();
		try{
			StringBuffer sql=new StringBuffer(" update UUM_USER@uum_link u set  u.password=:passWord where u.userid in (:userIds)");
			params.put("userIds", commond.getSearchUserIds());
			params.put("passWord", UserBean.defaultPassWord);
			int i=this.executeUpdate(QueryStringType.SQL, sql.toString(), params);
			if(i<1){
				flag=false;
			}
		}catch(Exception e){
			System.out.println("重置指定部委密码失败！");
			e.printStackTrace();
			flag=false;
		}
		return flag;
	}

	/**
	 * 获得UUM部委树
	 * @Date 2016-09-14
	 * @author RongSL
	 * */
	@Override
	public List<DepartmentBean> getUUMDepartmentsList(UserQueryCommond commond) {
		Map<String,Object> params=new HashMap<String,Object>();
		StringBuffer sql=new StringBuffer(" select to_char(department0_.DEPID)             as \"deptId\", " +
				"department0_.PARENT_ID         as \"parentId\", " +
				"department0_.DEPNAME           as \"depName\",  " +
				"department0_.DEPCODE           as \"depCode\", " +
				"department0_.TREEPATH          as \"treePath\", " +
				"department0_.ACTIVE_STATE      as \"activeState\", " +
				"department0_.ORDER_NUM         as \"orderNum\", " +
				"department0_.LAST_OPERATE_TIME as \"lastOperateTime\", " +
				"department0_.LAST_OPERATE_TYPE as \"lastOperateType\"  " +
				"from UUM_DEPARTMENT@uum_link department0_ " +
				"where 1=1  ");
		if(PropertyUtil.objectNotEmpty(commond.getDepParentId())){
			sql.append("  and department0_.PARENT_ID =:depParentId  ");
			params.put("depParentId", commond.getDepParentId());
		}
		if(PropertyUtil.objectNotEmpty(commond.getSearchDepCode())){
			sql.append(" and department0_.depCode=:depCode ");
			params.put("depCode", commond.getSearchDepCode());
		}
		if(PropertyUtil.objectNotEmpty(commond.getDepId())){
			sql.append(" and department0_.depId=:depId ");
			params.put("depId", commond.getDepId());
		}
		sql.append(" and department0_.ACTIVE_STATE =:activeState ");
		params.put("activeState", UserBean.ACTIVE_ENABLED);
		sql.append(" order by department0_.ORDER_NUM    ASC, department0_.ACTIVE_STATE DESC, department0_.DEPID        DESC  ");
		List<DepartmentBean> list=(List<DepartmentBean>) this.executeFind(QueryStringType.SQL, sql.toString(), params, DepartmentBean.class);
		return list;
	}
	
	/**
	 * 获得部委树
	 * @Date 2016-09-14
	 * @author RongSL
	 * */
	@Override
	public List<DepartmentBean> getDepartmentsList(UserQueryCommond commond) {
		Map<String,Object> params=new HashMap<String,Object>();
		StringBuffer sql=new StringBuffer(" select to_char(department0_.DEPID)             as \"deptId\", " +
				"department0_.PARENT_ID         as \"parentId\", " +
				"department0_.DEPNAME           as \"depName\",  " +
				"department0_.DEPt_CODE           as \"depCode\", " +
				"department0_.TREEPATH          as \"treePath\", " +
				"department0_.ACTIVE_STATE      as \"activeState\", " +
				"department0_.ORDER_NUM         as \"orderNum\" " +
				/*"department0_.LAST_OPERATE_TIME as \"lastOperateTime\", " +
				"department0_.LAST_OPERATE_TYPE as \"lastOperateType\"  " +*/
				"from base_DEPARTMENT department0_ " +
				"where 1=1  ");
		if(PropertyUtil.objectNotEmpty(commond.getDepParentId())){
			sql.append("  and department0_.PARENT_ID =:depParentId  ");
			params.put("depParentId", commond.getDepParentId());
		}
		if(PropertyUtil.objectNotEmpty(commond.getSearchDepCode())){
			sql.append(" and department0_.dept_Code=:depCode ");
			params.put("depCode", commond.getSearchDepCode());
		}
		if(PropertyUtil.objectNotEmpty(commond.getDepId())){
			sql.append(" and department0_.depId=:depId ");
			params.put("depId", commond.getDepId());
		}
		sql.append(" and department0_.ACTIVE_STATE =:activeState ");
		params.put("activeState", UserBean.ACTIVE_ENABLED);
		sql.append(" order by department0_.ORDER_NUM    ASC, department0_.ACTIVE_STATE DESC, department0_.DEPID        DESC  ");
		List<DepartmentBean> list=(List<DepartmentBean>) this.executeFind(QueryStringType.SQL, sql.toString(), params, DepartmentBean.class);
		return list;
	}
	
	/**
	 * 根据部委id查部委code
	 * @Date 2016-09-20
	 * */
	@Override
	public String getDeptCode(String deptId){
		String deptCode = null;
		String sql="select b.dept_code from base_department b where b.depid=:deptId";
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("deptId", deptId);
		List<String> list=(List<String>) this.executeFind(QueryStringType.SQL, sql.toString(), params);
		if(PropertyUtil.objectNotEmpty(list)&&PropertyUtil.objectNotEmpty(list.get(0))){
			deptCode=list.get(0);
		}
		return deptCode;
	}
}
